package org.ru.mse10.cvis.upload;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.ru.mse10.cvis.entity.cv.User;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * XML Parser class.
 * 
 * @author Spawn
 * 
 */
public class XMLParser extends DefaultHandler {

	/** The common. */
	private final CommonHandler<User> common = new UserXMLRowHandler();

	/** The temp user. */
	private User tempUser;

	/** The temp val. */
	private String tempVal;

	/**
	 * Method to read xml file.
	 * 
	 * @param in
	 *            - file name of xml that will be parsed
	 */
	public void parseXmlFile(InputStream in) {
		parseDocument(in);
	}

	/**
	 * Method to instance the doc builder and to parse the xml file.
	 * 
	 * @param in
	 *            - file name of xml file
	 */
	private void parseDocument(InputStream in) {

		// get a factory
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		try {

			// get a new instance of parser
			SAXParser saxParser = saxParserFactory.newSAXParser();
			// parse the file and also register this class for call backs
			saxParser.parse(in, this);

		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
	 * java.lang.String, java.lang.String, org.xml.sax.Attributes)
	 */
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		tempVal = "";
		if (qName.equalsIgnoreCase("user")) {
			// create a new instance of Student
			tempUser = new User();
			tempUser.setEmail(attributes.getValue("email"));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		tempVal = new String(ch, start, length);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
	 * java.lang.String, java.lang.String)
	 */
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {

		if (qName.equalsIgnoreCase("user")) {
			common.handle(tempUser);
			System.out.println(tempUser);
		} else if (qName.equalsIgnoreCase("id")) {
			tempUser.setId(Long.parseLong(tempVal));
		} else if (qName.equalsIgnoreCase("role")) {
			tempUser.setRole(common.getRole(tempVal));
		}
	}
}
